package com.ikkong.biz.service.impl;

import java.util.List;
import java.util.Map;

import com.google.common.collect.Maps;
import com.ikkong.core.base.service.impl.BaseService;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.toolbox.Record;
import com.ikkong.qy.util.WeixinApi;
import com.ikkong.biz.BizCst;
import com.ikkong.biz.model.Flow;
import com.ikkong.biz.model.FlowSegment;
import com.ikkong.biz.service.FlowSegmentService;
import com.ikkong.biz.service.FlowService;

/**
 * Generated by Blade.
 * 2016-11-24 10:55:05
 */
public class FlowSegmentServiceImpl extends BaseService<FlowSegment> implements FlowSegmentService{
	
	private FlowService flowService = new FlowServiceImpl();

	@Override
	public List<FlowSegment> findByFlowId(Object id) {
		Map<String,Object> map = Maps.newHashMap();
		map.put("flow_id",id);
		List<FlowSegment> fsegs = this.findBy("flow_id=#{flow_id}", map);
		return fsegs;
	}

	@Override
	public boolean next(FlowSegment flowSegment) {
		//更新上个节点为已处理
        FlowSegment prev = this.findFirst("select  *from tb_flow_segment where flow_id=#{flow_id} and stat=0 ", Record.create().set("flow_id", flowSegment.getFlow_id()));
        prev.setAttachUrl(flowSegment.getAttachUrl());
        prev.setComment(flowSegment.getComment());
        prev.setStat(1);
		this.update(prev);
		//流转到下个节点
		Flow flow = flowService.findById(flowSegment.getFlow_id());
		int opid = flowSegment.getOperator_id();
		
		//流程结束
		if(opid==-1){ 
			flowSegment.setStat(1);
			flow.setIs_end(BizCst.END);
		}
		flowSegment.setAttachUrl(null);
        flowSegment.setComment(null);
		int seg_id = this.saveRtId(flowSegment);
		WeixinApi.pushFlow(flow, prev, flowSegment);
		flow.setSeg_id(seg_id);
		return flowService.update(flow);
	}

}
